package org.spring.config.client.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;


/**
 * Copyright (c) 2017, com.ylink.,Ltd All Rights Reserved.<br/>
 * <b>包名称： </b>com.ylink.yfa4j.gateway.util<br/>
 * <b>文件名： </b>ShutdownServerUtil.java<br/>
 * <b>类描述： </b>关闭运行平台工具类<br/>
 * <b>时间： </b>2017年12月26日 下午3:36:24<br/>
 *
 * @author 于建军
 * @version v1.0
 */
public class ShutdownServerUtil {

    // 如果为true则是重启
    public static boolean isRestart = false;

    public static boolean isBat = true;

    public static void doShutdown() {
        try {
            if (isBat) {
                System.out.println("Restart Server Begin.............");
                String curPath = JarToolUtil.getLibPath("/config/");
                File subDir = new File(curPath);
                String exeCmd = "";
                if (isOSWindows()) {
                    exeCmd = "cmd.exe /C start startZuulServer.bat";

                    final Process process = Runtime.getRuntime()
                        .exec(new String[] {"cmd", "/c", "java -jar spring-config-client-0.0.1-SNAPSHOT.jar"});

                    printMessage(process.getInputStream());
                    printMessage(process.getErrorStream());
                    int value = process.waitFor();
                    System.out.println(value);

                } else {
                    exeCmd = "/bin/sh -c startWeb.sh";

                    // String command = "find " + source.getRoute() + " -name '" + source.getName();
                    //
                    // Process process = Runtime.getRuntime().exec(new String[] {"/bin/sh", "-c", command});
                }
                // Runtime.getRuntime().exec(exeCmd, null, subDir.getParentFile());
                System.out.println("Restart Server End.............");
                // Thread.sleep(10000);//等10秒，保证分身启动完成后，再关掉自己
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void printMessage(final InputStream input) {
        new Thread(new Runnable() {
            public void run() {

                Reader reader = new InputStreamReader(input);
                BufferedReader bf = new BufferedReader(reader);
                String line = null;
                try {
                    while ((line = bf.readLine()) != null) {
                        System.out.println(line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public static boolean isOSWindows() {
        String osName = System.getProperty("os.name");
//        if (Strings.isNullOrEmpty(osName)) {
//            return false;
//        }
        return osName.startsWith("Windows");
    }
}
